package com.gomore.opple.module.main.good;

import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.model.EventQueryShoppingCar;
import com.gomore.opple.model.Filter;
import com.gomore.opple.model.QueryFilter;
import com.gomore.opple.model.SecondFilter;
import com.gomore.opple.rest.common.DataPage;
import com.gomore.opple.rest.goods.GoodsCondition;
import com.gomore.opple.rest.goods.GoodsFilter;
import com.gomore.opple.rest.goods.GoodsResponse;
import com.gomore.opple.rest.shopcart.SaveShoppingCartRequest;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.web.cgform.goods.entity.TOGoodsEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by asus on 2016/12/27.
 */
public class GoodPresenter implements GoodContract.Presenter {
    private DataRepository mDataRepositroy;
    private final GoodContract.View mView;
    private CompositeSubscription mSubscriptions;
    private List<TOGoodsEntity> toGoodsEntities = new ArrayList<>();
    private List<Filter> filterList = new ArrayList<>();
    private int rows = GlobalConstant.PAGE_SIZE;
    private int page = GlobalConstant.PAGE_START;

    @Inject
    GoodPresenter(DataRepository dataRepository, GoodContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }

    @Override
    public void prepareInitData() {

    }

    @Override
    public void addToShoppingCar(SaveShoppingCartRequest saveShoppingCartRequest) {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.addToShoppingCar(saveShoppingCartRequest)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String string) {
                        super.onNext(string);
                        mView.hideProgressDialog();
                        //通知查询购物车
                        EventQueryShoppingCar eventQueryShoppingCar = new EventQueryShoppingCar();
                        eventQueryShoppingCar.setIsGetShoppingCar(true);
                        EventBus.getDefault().post(eventQueryShoppingCar);
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void queryGoods(QueryFilter queryFilter, final boolean loadMore, final boolean isFirst) {
        if (loadMore) {
            page++;
        } else {
            toGoodsEntities.clear();
            page = GlobalConstant.PAGE_START;
        }
        mView.showProgressDialog();
        GoodsCondition goodsCondition = new GoodsCondition();
        goodsCondition.setNameLike(queryFilter.getNameLike());
        goodsCondition.setStyleEquals(queryFilter.getStyleEquals());
        goodsCondition.setCategoryEquals(queryFilter.getCategoryEquals());
        goodsCondition.setSpaceEquals(queryFilter.getSpaceEquals());
        goodsCondition.setMaterialEqueals(queryFilter.getMaterialEqueals());
        goodsCondition.setStartprice(queryFilter.getStartprice());
        goodsCondition.setEndprice(queryFilter.getEndprice());
        DataPage dataPage = new DataPage();
        dataPage.setRows(rows);
        dataPage.setPage(page);
        goodsCondition.setPage(dataPage);
        mSubscriptions.clear();
        Subscription subscription = mDataRepositroy.queryGoods(goodsCondition)
                .map(new ServerResponseFunc<GoodsResponse>())
                .onErrorResumeNext(new HttpResponseFunc<GoodsResponse>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<GoodsResponse>() {
                    @Override
                    public void onNext(GoodsResponse goodsResponse) {
                        super.onNext(goodsResponse);
                        mView.hideProgressDialog();
                        if (loadMore) {
                            mView.showLoadMoreCompleted();
                        } else {
                            mView.showRefreshCompleted();
                        }
                        if (goodsResponse.getPage() <= goodsResponse.getTotalpages()) {
                            toGoodsEntities.addAll(goodsResponse.getGoodsEntity());
                        }
                        mView.showContent();
                        //第一次进来调用筛选条件
                        if (isFirst) {
                            getGoodsFilter();
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        if (loadMore) {
                            mView.showLoadMoreCompleted();
                        } else {
                            mView.showRefreshCompleted();
                        }
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void getGoodsFilter() {
        unsubscribe();
        mView.showProgressDialog();
        Subscription subscription = mDataRepositroy.getGoodsFilter()
                .map(new ServerResponseFunc<GoodsFilter>())
                .onErrorResumeNext(new HttpResponseFunc<GoodsFilter>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<GoodsFilter>() {
                    @Override
                    public void onNext(GoodsFilter goodsFilter) {
                        super.onNext(goodsFilter);
                        mView.hideProgressDialog();
                        filterList.addAll(translateGoodsFilter(goodsFilter));
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public List<TOGoodsEntity> getData() {
        return toGoodsEntities;
    }

    @Override
    public List<Filter> getFilter() {
        return filterList;
    }

    @Override
    public TOConsumerEntity getConsumer() {
        return mDataRepositroy.getConsumer();
    }

    @Override
    public void getGoodByBarCode(String barCode) {
        mView.showProgressDialog();
        mSubscriptions.clear();
        Subscription subscription = mDataRepositroy.getGoodsByCode(barCode)
                .map(new ServerResponseFunc<TOGoodsEntity>())
                .onErrorResumeNext(new HttpResponseFunc<TOGoodsEntity>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<TOGoodsEntity>() {
                    @Override
                    public void onNext(TOGoodsEntity toGoodsEntity) {
                        super.onNext(toGoodsEntity);
                        mView.hideProgressDialog();
                        mView.goGoodDetail(toGoodsEntity.getId());
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }

    private List<Filter> translateGoodsFilter(GoodsFilter goodsFilter) {
        // 风格(styles)，类型(categories)，空间(space)，材质(material)，价格(price)
        List<Filter> filterList = new ArrayList<>();
        //添加风格
        Filter filterStyles = new Filter();
        filterStyles.setCategory(GlobalConstant.FilterCategory.STYLES);
        filterStyles.setIsFirstCategory(true);
        filterStyles.setIsExpend(true);
        List<SecondFilter> stylesList = new ArrayList<>();
        for (int i = 0; i < goodsFilter.getStyles().size(); i++) {
            SecondFilter secondFilter = new SecondFilter();
            secondFilter.setCategory(GlobalConstant.FilterCategory.STYLES);
            secondFilter.setTypeName(goodsFilter.getStyles().get(i).getTypeName());
            secondFilter.setTypeCode(goodsFilter.getStyles().get(i).getTypecode());
            secondFilter.setIsSelect(false);
            stylesList.add(secondFilter);
        }
        filterStyles.setSecondFilterList(stylesList);
        filterList.add(filterStyles);
        //添加类型
        Filter filterCategories = new Filter();
        filterCategories.setCategory(GlobalConstant.FilterCategory.CATEGORIES);
        filterCategories.setIsFirstCategory(true);
        filterCategories.setIsExpend(true);
        List<SecondFilter> categoriesList = new ArrayList<>();
        filterCategories.setSecondFilterList(categoriesList);
        filterList.add(filterCategories);
        //添加类型下面的分类(跟外面大类是平行关系)
        for (int j = 0; j < goodsFilter.getCategories().size(); j++) {
            Filter filterInCategories = new Filter();
            filterInCategories.setCategory(goodsFilter.getCategories().get(j).getName());
            filterInCategories.setIsFirstCategory(false);
            filterInCategories.setIsExpend(true);
            List<SecondFilter> categoriesInList = new ArrayList<>();
            for (int k = 0; k < goodsFilter.getCategories().get(j).getChildren().size(); k++) {
                SecondFilter secondFilter = new SecondFilter();
                secondFilter.setCategory(GlobalConstant.FilterCategory.CATEGORIES);
                secondFilter.setTypeName(goodsFilter.getCategories().get(j).getChildren().get(k).getName());
                secondFilter.setTypeCode(goodsFilter.getCategories().get(j).getChildren().get(k).getId());
                secondFilter.setIsSelect(false);
                categoriesInList.add(secondFilter);
            }
            filterInCategories.setSecondFilterList(categoriesInList);
            filterList.add(filterInCategories);
        }
        //添加空间
        Filter filterSpace = new Filter();
        filterSpace.setCategory(GlobalConstant.FilterCategory.SPACE);
        filterSpace.setIsFirstCategory(true);
        filterSpace.setIsExpend(true);
        List<SecondFilter> spaceList = new ArrayList<>();
        for (int i = 0; i < goodsFilter.getSpace().size(); i++) {
            SecondFilter secondFilter = new SecondFilter();
            secondFilter.setCategory(GlobalConstant.FilterCategory.SPACE);
            secondFilter.setTypeName(goodsFilter.getSpace().get(i).getTypeName());
            secondFilter.setTypeCode(goodsFilter.getSpace().get(i).getTypecode());
            secondFilter.setIsSelect(false);
            spaceList.add(secondFilter);
        }
        filterSpace.setSecondFilterList(spaceList);
        filterList.add(filterSpace);
        //添加材料
        Filter filterMaterial = new Filter();
        filterMaterial.setCategory(GlobalConstant.FilterCategory.MATERIAL);
        filterMaterial.setIsFirstCategory(true);
        filterMaterial.setIsExpend(true);
        List<SecondFilter> materialList = new ArrayList<>();
        for (int i = 0; i < goodsFilter.getMaterial().size(); i++) {
            SecondFilter secondFilter = new SecondFilter();
            secondFilter.setCategory(GlobalConstant.FilterCategory.MATERIAL);
            secondFilter.setTypeName(goodsFilter.getMaterial().get(i).getTypeName());
            secondFilter.setTypeCode(goodsFilter.getMaterial().get(i).getTypecode());
            secondFilter.setIsSelect(false);
            materialList.add(secondFilter);
        }
        filterMaterial.setSecondFilterList(materialList);
        filterList.add(filterMaterial);
        //添加价格
        Filter filterPrice = new Filter();
        filterPrice.setCategory(GlobalConstant.FilterCategory.PRICE);
        filterPrice.setIsFirstCategory(true);
        filterPrice.setIsExpend(true);
        List<SecondFilter> priceList = new ArrayList<>();
        for (int i = 0; i < goodsFilter.getPrice().size(); i++) {
            SecondFilter secondFilter = new SecondFilter();
            secondFilter.setCategory(GlobalConstant.FilterCategory.PRICE);
            secondFilter.setTypeName(goodsFilter.getPrice().get(i).getTypeName());
            secondFilter.setTypeCode(goodsFilter.getPrice().get(i).getTypecode());
            secondFilter.setIsSelect(false);
            priceList.add(secondFilter);
        }
        filterPrice.setSecondFilterList(priceList);
        filterList.add(filterPrice);
        return filterList;
    }
}
